package main;

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
import freemarker.ext.beans.BeansWrapper;
import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;
import freemarker.template.TemplateHashModel;
import ldh.maker.database.TableInfo;
import ldh.maker.freemaker.FreeMarkerMaker;
import ldh.maker.util.FreeMakerUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.net.InetSocketAddress;
import java.util.HashMap;
import java.util.Map;

public class MyHttpServer {

	protected Configuration cfg = new Configuration();
	
	protected Logger logger = LoggerFactory.getLogger(FreeMarkerMaker.class);
	
	private TableInfo tableInfo = null;
	
	private Template indexTemp = null;
	
	
	
	public static void main(String[] args) throws IOException {
		MyHttpServer server = new MyHttpServer();
		
		server.start();
	}
	
	public void start() throws IOException {
		init();
		HttpServer server = HttpServer.create(new InetSocketAddress(
				"127.0.0.1", 9999), 0);
		server.createContext("/", new MyResponseHandler());
		server.setExecutor(null); // creates a default executor
		server.start();
		System.out.println("OK");
	}
	
	private void init() {
		freeMakerInit();
		try {
			indexTemp = cfg.getTemplate("index.ftl");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public class MyResponseHandler implements HttpHandler {
		public void handle(HttpExchange t) throws IOException {
			Map<Object, Object> data = new HashMap<Object, Object>();
			String query = t.getRequestURI().getRawQuery();
			System.out.println(query);
			if (t.getRequestURI().getPath().equals("/index")) {
				if (tableInfo == null) {
//					MyMapper other = new MyMapper();
//					other.table("scenic").other("status", Status.class);
//					other.all("status", Status.class);
					tableInfo = new TableInfo(null, null, null);
				}
				
				data.put("tableInfo", tableInfo);
				
				String dd = databaseInfo(data);
				byte[] responseData = dd.getBytes("utf-8");
				t.sendResponseHeaders(200, responseData.length);
//				t.getResponseBody().write("阿发".getBytes());
				t.getResponseBody().write(responseData);
				t.close();
			} else if (t.getRequestURI().equals("post")) {
				String response = "http://localhost:9999/index";
				t.getResponseHeaders().add("location", response);
				t.sendResponseHeaders(301, response.length());
				t.close();
			}
			String error = "error!!!";
			t.sendResponseHeaders(200, error.length());
			t.getResponseBody().write(error.getBytes("utf-8"));
			t.close();
		}
		
		
		public String databaseInfo(Map<Object, Object> data) {
			StringWriter writer = null;
			try {
				writer = new StringWriter();
		        indexTemp.process(data, writer);
		        writer.flush();
		        writer.close();
				return writer.toString();
			} catch (Exception e) {
				logger.error("freemaker init error!!!!!!!!!!!!1", e);
			} finally {
				if (writer != null) {
					try {
						writer.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
			return null;
		}
	}
	
	private void freeMakerInit() {
		BeansWrapper wrapper = BeansWrapper.getDefaultInstance();
		TemplateHashModel staticModels = wrapper.getStaticModels();
		TemplateHashModel fileStatics;
		try {
			fileStatics = (TemplateHashModel) staticModels.get(FreeMakerUtil.class.getName());
			cfg.setSharedVariable("util", fileStatics);
			String ftlPath = FreeMarkerMaker.class.getResource("/index.ftl").getPath();
			File file = new File(ftlPath);
			cfg.setDirectoryForTemplateLoading(file.getParentFile());
			cfg.setObjectWrapper(new DefaultObjectWrapper());
		} catch (Exception e) {
			logger.error("freemaker init error!!!!!!!!!!!!1", e);
		}
	}
	
	
}
